﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics.Contracts;
using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IProductQuestionRepository))]
    public partial class EntityRepositories:IProductQuestionRepository
    {
        #region ProductQuestion


        public IQueryable<IProductQuestion> ProductQuestions
        {
            get
            {
                return this.DataReaderContext.ProductQuestions;
            }
        }

        public void Post(IProductQuestion productQuestion)
        {
            Contract.Requires(productQuestion != null);

            var item = new ProductQuestion()
            {
                Answer = productQuestion.Answer,
                AnswerDate = productQuestion.AnswerDate,
                AnsweredBy = productQuestion.AnsweredBy,
                ProductId = productQuestion.Product.Id,
                Question = productQuestion.Question,
                QuestionBy = productQuestion.QuestionBy,
                QuestionDate = productQuestion.QuestionDate,
                QuestionEmail = productQuestion.QuestionEmail
            };

            this.DataWriterContext.ProductQuestions.InsertOnSubmit(item);
            this.DataWriterContext.SubmitChanges();
        }

        public void Put(IProductQuestion productQuestion)
        {
            Contract.Requires(productQuestion != null);

            var item = this.DataWriterContext.ProductQuestions
                .Where(i => i.Id == productQuestion.Id)
                .FirstOrDefault();

            if (item == null)
            {
                throw new KeyNotFoundException("ProductQuestion: " + productQuestion.Id);

            }

            item.Answer = productQuestion.Answer;
            item.AnswerDate = productQuestion.AnswerDate;
            item.AnsweredBy = productQuestion.AnsweredBy;
            item.ProductId = productQuestion.Product.Id;
            item.Question = productQuestion.Question;
            item.QuestionBy = productQuestion.QuestionBy;
            item.QuestionDate = productQuestion.QuestionDate;
            item.QuestionEmail = productQuestion.QuestionEmail;

            this.DataWriterContext.SubmitChanges();
        }

        public void Delete(IProductQuestion productQuestion)
        {
            if (productQuestion != null)
            {
                var item = this.DataWriterContext.ProductQuestions
                .Where(i => i.Id == productQuestion.Id)
                .FirstOrDefault();

                if (item != null)
                {
                    this.DataWriterContext.ProductQuestions.DeleteOnSubmit(item);
                    this.DataWriterContext.SubmitChanges();
                }
            }
        }

        #endregion
    }
}
